
<script setup>
import { reactive, watch, h, computed, onMounted, ref, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
const { Bus } = getCurrentInstance().appContext.config.globalProperties;

const userstore=useUserStore();
const router = useRouter();
const state = reactive({
    collapsed: false,
    selectedKeys: ['/crm/data-board'],
    openKeys: ['sub1'],
    preOpenKeys: ['sub1'],
});
const currentRoute = ref("/crm")
const items = reactive([]);
const routerList =ref([
    {
        label: '首页',
        key: '/home',
        icon: () => h('span', { class: 'icon icon-home' }),
    },
]);
watch(
    () => state.openKeys,
    (_val, oldVal) => {
        state.preOpenKeys = oldVal;  
    },
);
Bus.on('changeNav', () => {
   
})
onMounted(() => {
    getMenu();
    if(sessionStorage.getItem('selectedKeys')){
        state.selectedKeys=JSON.parse(sessionStorage.getItem('selectedKeys'))
    }
    getNav()
})
const getNav = () => {
    if (sessionStorage.getItem("oneUrl")) {
        currentRoute.value = sessionStorage.getItem("oneUrl");
    }
}
const getMenu=()=>{
    routerList.value=[];
    let list = userstore.menuList.filter(item => !item.meta.hidden);
    let routerArray=changRouterList(list);
    console.log(routerArray);
    routerList.value=[...routerList.value,...routerArray];
}
const changRouterList = (options) => {
    let list =[]
    options.forEach((item) => {
        if (item.meta.hidden) {
            return
        }
        let e_new = {
            label:item.meta.title,
            key:item.path,
            icon: () => h('span',{class:`icon  icon-${item.meta.icon}`}),
        };
        if(item.meta.hidden) return;
        if (item.children && item.children.length >=1&&!item.children[0].meta.hidden){
            const children = changRouterList(item.children);
            // 保存权限
            e_new = {
                ...e_new,
                children: children
            };
        }
        list.push(e_new);
    })
    return list
}
const toggleCollapsed = () => {
    state.collapsed = !state.collapsed;
    state.openKeys = state.collapsed ? [] : state.preOpenKeys;
};
const handleClickRoute = (options) => {
    state.selectedKeys=options.keyPath
    sessionStorage.setItem('selectedKeys',JSON.stringify(options.keyPath))
    router.push({
        path: options.keyPath[options.keyPath.length - 1]
    })
}


</script>
<template>
    <a-menu v-model:openKeys="state.openKeys" v-model:selectedKeys="state.selectedKeys" mode="inline"
        :inline-collapsed="state.collapsed" :items="routerList" @click="handleClickRoute"></a-menu>
</template>
<style lang='scss' scoped>
:deep(.ant-menu-light) {
    background: var(--themeColor);
}
</style>